package com.ruoyi.web.controller.tool;

import com.ruoyi.system.domain.GwHomeSummarize;
import com.ruoyi.system.service.IGwHomeSummarizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class EncryptionUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final int KEY_SIZE = 128;
    private static final SecureRandom RANDOM = new SecureRandom();
    private final SecretKey secretKey;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public EncryptionUtil() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE, RANDOM);
        this.secretKey = keyGenerator.generateKey();
    }

    public String encrypt(Object obj) throws Exception {
        String json = objectMapper.writeValueAsString(obj);
        byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        byte[] iv = new byte[16];
        RANDOM.nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        byte[] encryptedData = cipher.doFinal(jsonBytes);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(iv);
        outputStream.write(encryptedData);
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    // 注意：解密方法通常不会在前端使用，这里仅供后端测试或内部使用
    public <T> T decrypt(String encryptedData, Class<T> clazz) throws Exception {
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] iv = new byte[16];
        byte[] encryptedDataBytes = new byte[decodedBytes.length - 16];
        System.arraycopy(decodedBytes, 0, iv, 0, 16);
        System.arraycopy(decodedBytes, 16, encryptedDataBytes, 0, decodedBytes.length - 16);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

        String json = new String(decryptedBytes, StandardCharsets.UTF_8);
        return objectMapper.readValue(json, clazz);
    }

    // 密钥获取方法（仅用于测试或初始化，实际应用中应通过安全方式获取密钥）
    public String getSecretKeyBase64() {
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }






}